package com.baijiayun.liveuibase.widgets.courseware;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baijiayun.livecore.context.LPConstants;
import com.baijiayun.livecore.models.LPDocTranslateProgressModel;
import com.baijiayun.livecore.models.LPUploadDocumentUserModel;
import com.baijiayun.livecore.models.courseware.LPCoursewareModel;
import com.baijiayun.livecore.models.file.cloudfile.LPCloudFileModel;
import com.baijiayun.livecore.models.file.homework.LPHomeworkModel;
import com.baijiayun.livecore.utils.LPLogger;
import com.baijiayun.livecore.viewmodels.impl.LPDocListViewModel;
import com.baijiayun.liveuibase.base.BaseUIConstant.FileUploadState;
import com.baijiayun.liveuibase.base.BaseUIConstant.HomeworkDownloadState;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.utils.BaseUIUtils;
import com.baijiayun.liveuibase.widgets.common.ProgressCircleView;
import com.baijiayun.liveuibase.widgets.common.StateTextView;
import com.baijiayun.liveuibase.widgets.courseware.models.DownloadHomeworkModel;
import com.baijiayun.liveuibase.widgets.courseware.models.UploadDocModel;
import com.baijiayun.liveuibase.widgets.popupwindow.ErrorDesPopupWindow;

import org.w3c.dom.Text;

import java.io.File;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static com.baijiayun.liveuibase.base.BaseUIConstant.ERROR_CODE_UPLOAD_FAIL_CANT_REUPLOAD_CUSTOM_CODE;
import static com.baijiayun.liveuibase.base.BaseUIConstant.homeworkDirPath;

public class BaseCourseWareFileViewHolder extends RecyclerView.ViewHolder {
    private final static String tag = BaseCourseWareFileViewHolder.class.getSimpleName();
    private final int undefinedFileSize = -1;
    private View vSticky;
    private ImageView ivFileIcon;
    private TextView tvFileName;

    private Context mContext;
    private View mView;
    // 当前用户角色 为 老师或助教
    private boolean mIsTeacherOrAssistant;
    private IOnDocItemClickListener onItemClickListener;
    private boolean isAnim;

    public BaseCourseWareFileViewHolder(View itemView, boolean isTeacherOrAssistant) {
        super(itemView);
        mContext = itemView.getContext();
        mView = itemView;
        mIsTeacherOrAssistant = isTeacherOrAssistant;
        vSticky = findView(R.id.base_course_file_item_sticky_icon);
        ivFileIcon = findView(R.id.base_course_file_item_icon);
        tvFileName = findView(R.id.base_course_file_item_name);

        initDocView();
        initUploadingView();
        initHomeworkView();
        initCloudView();
    }

    /**
     * 初始化 已有 的文档视图
     */
    public void initDocModel(LPCoursewareModel coursewareModel) {
        docContainer.setVisibility(VISIBLE);
        uploadContainer.setVisibility(GONE);
        homeworkContainer.setVisibility(GONE);
        cloudContainer.setVisibility(GONE);
        initUploadSrc(coursewareModel.bindSource == LPConstants.BINDER_SOURCE_LOCAL);
        ivDocDelete.setEnabled(coursewareModel.bindSource == LPConstants.BINDER_SOURCE_LOCAL);

        if(coursewareModel.coursewareType == LPCoursewareModel.LPCoursewareType.DOC) {
            LPDocListViewModel.DocModel docModel = ((LPDocListViewModel.DocModel)coursewareModel);
            setIsAnim(!TextUtils.isEmpty(docModel.pptUrl));
            if(docModel.isEnableRecord) {
                setNameAndType(coursewareModel.name);
                ivDocPlay.setEnabled(false);
                ivDocPlay.setAlpha(0.3f);
                setFileSize(tvDocSize, undefinedFileSize);
                return;
            }
        } else {
            setIsAnim(false);
        }

        setFileName(coursewareModel.name);
        String ext = coursewareModel.ext;
        int indexOf = coursewareModel.name.lastIndexOf(".");
        if(indexOf != -1) {
            ext = coursewareModel.name.substring(indexOf);
        }
        setFileType(ext);
        ivDocPlay.setEnabled(true);
        ivDocPlay.setAlpha(1f);
        setFileUserName(tvDocUserName,coursewareModel.userModel);
        setFileSize(tvDocSize, coursewareModel.size);
    }

    /**
     * 初始化 上传中 的文档视图
     */
    public void initDocModel(UploadDocModel uploadDocModel) {
        docContainer.setVisibility(GONE);
        uploadContainer.setVisibility(VISIBLE);
        homeworkContainer.setVisibility(GONE);
        cloudContainer.setVisibility(GONE);
        setIsAnim(uploadDocModel.isAnim());

        try {
            String[] fragments = uploadDocModel.getPath().split("/");
            setNameAndType(fragments[fragments.length - 1]);
        } catch (Exception e) {
            setFileName("未知文件");
            setFileType("");
        }

        setFileState(uploadDocModel.getNowState());

        this.errorModel = uploadDocModel.getErrorModel();
        if (errorModel != null) {
            checkErrorType(errorModel.errorType);
            ivUploadReUpload.setVisibility(canReUpload ? VISIBLE : GONE);
            ivUploadByNormal.setVisibility(canReUpload && isAnim ? VISIBLE : GONE);
        }
    }

    /**
     * 初始化 作业视图
     */
    public void initDocModel(LPHomeworkModel homeworkModel) {
        docContainer.setVisibility(GONE);
        uploadContainer.setVisibility(GONE);
        homeworkContainer.setVisibility(VISIBLE);
        cloudContainer.setVisibility(GONE);
        setFileName(homeworkModel.getName());
        setFileType(homeworkModel.getFext());
        setIsAnim(homeworkModel.isAnim());
        setFileSize(tvHomeworkSize, homeworkModel.getSize());
        setTextView(tvHomeworkUserName, homeworkModel.getUserModel().getUserName());
        setTextView(tvHomeworkUploadTime, BaseUIUtils.formatDateAndTimeByLong(homeworkModel.getLastModifiedTime()));

        ivHomeworkPlay.setVisibility(homeworkModel.isCanPreview() ? VISIBLE : INVISIBLE);
        boolean needSticky = homeworkModel.getBindSource() == LPConstants.BINDER_SOURCE_BACK_STAGE
                || homeworkModel.getUserModel().getUserType() == LPConstants.LPUserType.Teacher
                || homeworkModel.getUserModel().getUserType() == LPConstants.LPUserType.Assistant;
        if (needSticky) {
            vSticky.setVisibility(VISIBLE);
            mView.setBackground(new ColorDrawable(ContextCompat.getColor(mContext, R.color.base_divider_line_other)));
        }
        ivHomeworkDelete.setEnabled(homeworkModel.getBindSource() == LPConstants.BINDER_SOURCE_LOCAL);

        this.mHomeworkModel = homeworkModel;

        if (!mIsTeacherOrAssistant) {
            // 非老师或助教，不显示 播放 & 删除按钮
            ivHomeworkDelete.setVisibility(GONE);
            ivHomeworkPlay.setVisibility(GONE);
        }
    }

    /**
     * 初始化 云盘文件视图
     */
    public void initDocModel(LPCloudFileModel cloudFileModel) {
        docContainer.setVisibility(GONE);
        uploadContainer.setVisibility(GONE);
        homeworkContainer.setVisibility(GONE);
        cloudContainer.setVisibility(VISIBLE);

        setFileName(cloudFileModel.getName());
        isCloudDirectory = cloudFileModel.isDirectory();
        if (cloudFileModel.isDirectory()) {
            setIcon(R.drawable.base_course_ware_type_directory);
            setTextView(tvCloudSize, "-");
            ivCloudPlay.setVisibility(INVISIBLE);
            ivCloudDelete.setVisibility(INVISIBLE);
        } else {
            String ext = cloudFileModel.getFExt();
            int indexOf = cloudFileModel.getName().lastIndexOf(".");
            if(indexOf != -1) {
                ext = cloudFileModel.getName().substring(indexOf);
            }
            setFileType(ext);

            setIsAnim(cloudFileModel.getFileType() == LPConstants.LPFileType.Anim);
            long size = 0;
            try {
                size = cloudFileModel.getSize();
            } catch (Exception e) {
                e.printStackTrace();
            }
            setFileSize(tvCloudSize, size);
            ivCloudPlay.setVisibility(VISIBLE);
            ivCloudDelete.setVisibility(cloudFileModel.isPublicFile() ? INVISIBLE : VISIBLE);
        }
        setTextView(tvCloudTime, BaseUIUtils.formatDateAndTimeByLong(cloudFileModel.getCreateTime()));
    }

    /**
     * ViewHolder复用时，调用此方法以重置视图
     */
    public void resetView() {
        if (downloadHomeworkModel != null) {
            // 复用 viewHolder 时，清空之前的 download 视图信息
            downloadHomeworkModel.setItemView(null);
            downloadHomeworkModel = null;
        }
        updateDownloadProgress(0);
        vSticky.setVisibility(GONE);
        mView.setBackground(null);
        initUploadSrc(true);
        resetDownLoadProgress();
        setIsAnim(false);
    }

    public void setOnItemClickListener(IOnDocItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    /**
     * 上传中的文件，调用此方法传入 state 以更新当前上传状态
     */
    public void setFileState(FileUploadState state) {
        mNowState = state;
        ivUploadDelete.setVisibility(state != FileUploadState.Uploading ? VISIBLE : INVISIBLE);
        ivUploadReUpload.setVisibility(state.isFailed() ? VISIBLE : INVISIBLE);
        tvUploadFailDir.setVisibility(state.isFailed() ? VISIBLE : INVISIBLE);
        ivUploadByNormal.setVisibility(state.isFailed() && isAnim ? VISIBLE : INVISIBLE);
        tvUploadFileState.setEnabled(!state.isFailed());
        tvUploadCancel.setVisibility(state == FileUploadState.Uploading ? VISIBLE : GONE);
        switch (state) {
            case UploadSuccess:
                setTextView(tvUploadFileState, mContext.getString(R.string.base_course_manage_upload_state_ok));
                break;
            case Translating:
                setTextView(tvUploadFileState, mContext.getString(R.string.base_course_manage_upload_state_translating));
                break;
            case Uploading:
                setTextView(tvUploadFileState, mContext.getString(R.string.base_course_manage_upload_state_uploading));
                break;
            case TranslateFailed:
                setTextView(tvUploadFileState, mContext.getString(R.string.base_course_manage_upload_state_translate_failed));
                break;
            case UploadFailed:
                setTextView(tvUploadFileState, mContext.getString(R.string.base_course_manage_upload_state_upload_failed));
                break;
            default:
                break;
        }
    }

    // region 下载中 model，视图绑定时初始化，解除绑定时需要清空
    private DownloadHomeworkModel downloadHomeworkModel;

    public void setDownloadHomeworkModel(DownloadHomeworkModel downloadHomeworkModel) {
        this.downloadHomeworkModel = downloadHomeworkModel;
    }
    // endregion

    public void updateDownloadProgress(float progress) {
        ivHomeworkDownloadProgress.setRatio(progress);
    }

    /**
     * 展示下载失败
     */
    public void showDownLoadFailed() {
        File file = checkHomeworkFile(mHomeworkModel);
        if (homeworkDownloadState == HomeworkDownloadState.Downloading) {
            // 如果下载中，则需要删除失败的文件，并展示视图
            boolean rst = file.delete();
            if (rst) {
                checkHomeworkFile(mHomeworkModel);
                updateDownloadProgress(0);
                ivHomeworkDownloadProgress.setVisibility(INVISIBLE);
                ivHomeworkDownload.setImageDrawable(ContextCompat.getDrawable(
                        mContext, R.drawable.base_ic_course_ware_download_fail));
            }
            homeworkDownloadState = HomeworkDownloadState.DownloadFailed;
        }
    }

    /**
     * 重置下载状态进度视图
     */
    public void resetDownLoadProgress() {
        ivHomeworkDownload.setImageDrawable(ContextCompat.getDrawable(
                mContext, R.drawable.base_ic_course_ware_download));
        updateDownloadProgress(0);
        ivHomeworkDownloadProgress.setVisibility(VISIBLE);
    }

    private void setFileSize(TextView tv, long kbSize) {
        if (kbSize == undefinedFileSize) {
            setTextView(tv, "-");
        } else {
            float size = (float) kbSize / 1024;
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            if (size < 1024) {
                setTextView(tv, df.format(size) + "K");
            } else {
                setTextView(tv, df.format(size / 1024) + "M");
            }
        }
    }

    private void setFileUserName(TextView tv, LPUploadDocumentUserModel userModel){
        if(userModel==null){
            setTextView(tv,"");
        }else{
            setTextView(tv,userModel.userName);
        }
    }

    private void setFileName(String fileName) {
        setTextView(tvFileName, fileName);
    }

    private void initUploadSrc(boolean uploadByLocal) {
        ivDocRelate.setVisibility(uploadByLocal ? GONE : VISIBLE);
    }

    private void setFileType(String ext) {
        if (TextUtils.isEmpty(ext) || !ext.contains(".")) {
            setIcon(R.drawable.base_course_ware_type_error);
        } else {
            switch (ext.toLowerCase()) {
                case ".ppt":
                case ".pptx":
                    if (isAnim) {
                        setIcon(R.drawable.base_course_ware_type_ppt_anim);
                    } else {
                        setIcon(R.drawable.base_course_ware_type_ppt_static);
                    }
                    break;
                case ".txt":
                    setIcon(R.drawable.base_course_ware_type_txt);
                    break;
                case ".xls":
                    setIcon(R.drawable.base_course_ware_type_xls);
                    break;
                case ".doc":
                case ".docx":
                    setIcon(R.drawable.base_course_ware_type_doc);
                    break;
                case ".pdf":
                    setIcon(R.drawable.base_course_ware_type_pdf);
                    break;
                case ".zip":
                case ".bjon":
                    setIcon(R.drawable.base_course_ware_type_zip);
                    break;
                case ".png":
                case ".jpg":
                case ".jpeg":
                case ".webp":
                case ".bmp":
                    setIcon(R.drawable.base_course_ware_type_img);
                    break;
                case ".mp3":
                case ".wav":
                case ".wma":
                case ".aac":
                case ".flac":
                case ".m4a":
                case ".oga":
                case ".opus":
                    setIcon(R.drawable.base_course_ware_type_audio);
                    break;
                case ".mp4":
                case ".3gp":
                case ".mpg":
                case ".mpeg":
                case ".3g2":
                case ".avi":
                case ".flv":
                case ".wmv":
                case ".h264":
                case ".m4v":
                case ".mj2":
                case ".mov":
                case ".ogg":
                case ".ogv":
                case ".rm":
                case ".rmvb":
                case ".qt":
                case ".webm":
                    setIcon(R.drawable.base_course_ware_type_video);
                    break;
                case ".html":
                    setIcon(R.drawable.base_course_ware_type_h5);
                    break;
                case ".bds":
                    setIcon(R.drawable.base_course_ware_type_bds);
                    break;
                default:
                    setIcon(R.drawable.base_course_ware_type_error);
                    break;
            }
        }
    }

    private void setIcon(int resId) {
        ivFileIcon.setImageResource(resId);
    }

    private void setIsAnim(boolean isAnim) {
        this.isAnim = isAnim;
        if (isAnim) {
            ivFileIcon.setImageResource(R.drawable.base_course_ware_type_ppt_anim);
        }
    }

    private void setTextView(TextView textView, String string) {
        if (textView != null) {
            textView.setText(string);
        }
    }

    private void setNameAndType(String wholeName) {
        String[] values = wholeName.split("\\.");
        if (values.length > 0) {
            setFileName(wholeName.substring(0, wholeName.length() - values[values.length - 1].length() - 1));
            setFileType("." + values[values.length - 1]);
        }
    }

    private String checkErrorType(int errorType) {
        if (errorType != 10012 && errorType != 10011 && errorType != ERROR_CODE_UPLOAD_FAIL_CANT_REUPLOAD_CUSTOM_CODE) {
            canReUpload = true;
        }
        switch (errorType) {
            case ERROR_CODE_UPLOAD_FAIL_CANT_REUPLOAD_CUSTOM_CODE:
                return errorModel.errMsg;
            case 10001:
                return "下载文件失败";
            case 10002:
                return "office转PDF失败";
            case 10003:
                return "pdf转png失败";
            case 10005:
                return "动画转html失败";
            case 10004:
                return "上传静态文件失败";
            case 10006:
                return "打包动画文件失败";
            case 10007:
                return "压缩动画文件失败";
            case 10008:
                return "上传动画压缩文件失败";
            case 10009:
                return "上传动画html失败";
            case 10010:
                return "转码失败";
            case 10011:
                return "文件被加密，请上传非加密文件";
            case 10012:
                return "请删除隐藏页或另存为pptx格式文件";
            default:
                return "未知错误";
        }
    }

    /**
     * doc item 事件回调
     */
    public interface IOnDocItemClickListener {
        void onPlay();

        void onDelete(String id);
    }

    /**
     * 上传中 item 事件回调
     */
    public interface IOnUploadItemClickListener extends IOnDocItemClickListener {
        void onUploadByNormal();

        void onReUpload(String fileId);

        void onCancelUpload();

        void onCancelTransfer();
    }

    /**
     * 作业 item 事件回调
     */
    public interface IOnHomeworkItemClickListener extends IOnDocItemClickListener {
        void onDownload(File file);

        void onCancelDownload(File file);
    }

    /**
     * 云盘 item 事件回调
     */
    public interface IOnCloudItemClickListener extends IOnDocItemClickListener {
        /**
         * 文件夹点击事件
         */
        void onClickDirectory();
    }

    // region 已有 doc 控件
    private RelativeLayout docContainer;
    private ImageView ivDocRelate;
    private ImageView ivDocDelete;
    private ImageView ivDocPlay;
    private TextView tvDocSize;
    private TextView tvDocUserName;

    void initDocView() {
        docContainer = findView(R.id.base_course_file_item_doc_container);
        ivDocPlay = findView(R.id.base_course_file_item_doc_play);
        ivDocDelete = findView(R.id.base_course_file_item_doc_delete);
        ivDocRelate = findView(R.id.base_course_file_item_doc_is_relate);
        tvDocSize = findView(R.id.base_course_file_item_doc_size);
        tvDocUserName = findView(R.id.base_course_file_item_doc_user_name);
        ivDocPlay.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onPlay();
            }
        });
        ivDocDelete.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onDelete(errorModel == null ? "" : errorModel.fid);
            }
        });
    }
    // endregion

    // region 上传中 控件
    private RelativeLayout uploadContainer;
    private StateTextView tvUploadFileState;
    private ImageView ivUploadDelete;
    private ImageView ivUploadReUpload;
    private ImageView ivUploadByNormal;
    private TextView tvUploadFailDir;
    private TextView tvUploadCancel;

    private boolean canReUpload = false;
    private LPDocTranslateProgressModel errorModel;
    private ErrorDesPopupWindow errorDesPopupWindow;
    private FileUploadState mNowState;

    void initUploadingView() {
        uploadContainer = findView(R.id.base_course_file_item_uploading_container);
        tvUploadFileState = findView(R.id.base_course_file_item_state);
        ivUploadDelete = findView(R.id.base_course_file_item_delete_uploading);
        ivUploadReUpload = findView(R.id.base_course_file_item_re_upload);
        ivUploadByNormal = findView(R.id.base_course_file_item_upload_by_normal);
        tvUploadFailDir = findView(R.id.base_course_file_item_fail_dir);
        tvUploadCancel = findView(R.id.base_course_file_item_upload_cancel);
        tvUploadCancel.setOnClickListener(v -> (
                (IOnUploadItemClickListener) onItemClickListener).onCancelUpload());
        ivUploadDelete.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                if (mNowState == FileUploadState.Translating) {
                    // 当前处于转码状态，取消转码
                    ((IOnUploadItemClickListener) onItemClickListener).onCancelTransfer();
                } else if (errorModel != null) {
                    // 已失败，移除视图。注：因为 uploading & uploadSuccess 两个状态 delete 按钮不可见
                    onItemClickListener.onDelete(errorModel.fid);
                }
            }
        });
        tvUploadFailDir.setOnClickListener(v -> {
            if (errorModel == null) {
                return;
            }
            if (errorDesPopupWindow == null) {
                errorDesPopupWindow = new ErrorDesPopupWindow(mContext);
            }
            errorDesPopupWindow.updateErrorMsg(checkErrorType(errorModel.errorType));
            errorDesPopupWindow.show(tvUploadFailDir);
        });
        ivUploadByNormal.setOnClickListener(v -> {
            if (onItemClickListener instanceof IOnUploadItemClickListener) {
                ((IOnUploadItemClickListener) onItemClickListener).onUploadByNormal();
            }
        });
        ivUploadReUpload.setOnClickListener(v -> {
            if (onItemClickListener instanceof IOnUploadItemClickListener && errorModel != null) {
                ((IOnUploadItemClickListener) onItemClickListener).onReUpload(errorModel.fid);
            }
        });
    }
    // endregion

    // region 云盘控件
    RelativeLayout cloudContainer;
    private ImageView ivCloudDelete;
    private TextView tvCloudSize;
    private TextView tvCloudTime;
    private ImageView ivCloudPlay;

    void initCloudView() {
        cloudContainer = findView(R.id.base_course_file_item_cloud_container);
        ivCloudPlay = findView(R.id.base_course_file_item_cloud_play);
        ivCloudDelete = findView(R.id.base_course_file_item_cloud_delete);
        tvCloudSize = findView(R.id.base_course_file_item_cloud_size);
        tvCloudTime = findView(R.id.base_course_file_item_cloud_upload_time);
        ivCloudPlay.setOnClickListener(v -> onItemClickListener.onPlay());
        ivCloudDelete.setOnClickListener(v -> onItemClickListener.onDelete(""));

        mView.setOnClickListener(v -> {
            if (isCloudDirectory && onItemClickListener instanceof IOnCloudItemClickListener) {
                // 云盘文件夹点击事件，打开文件夹
                ((IOnCloudItemClickListener) onItemClickListener).onClickDirectory();
            }
        });
    }

    boolean isCloudDirectory;
    // endregion

    // region 作业控件
    private RelativeLayout homeworkContainer;
    private ImageView ivHomeworkDelete;
    private ImageView ivHomeworkOpenFile;
    private ImageView ivHomeworkDownload;
    private ProgressCircleView ivHomeworkDownloadProgress;
    private ImageView ivHomeworkPlay;
    private TextView tvHomeworkUploadTime;
    private TextView tvHomeworkUserName;
    private TextView tvHomeworkSize;

    private LPHomeworkModel mHomeworkModel;

    void initHomeworkView() {
        homeworkContainer = findView(R.id.base_course_file_item_homework_container);
        ivHomeworkDelete = findView(R.id.base_course_file_item_delete_homework);
        ivHomeworkOpenFile = findView(R.id.base_course_file_item_open_file);
        ivHomeworkDownload = findView(R.id.base_course_file_item_download);
        ivHomeworkDownloadProgress = findView(R.id.base_course_file_item_download_progress);
        updateDownloadProgress(0);
        ivHomeworkPlay = findView(R.id.base_course_file_item_play_homework);
        tvHomeworkUploadTime = findView(R.id.base_course_file_item_homework_upload_time);
        tvHomeworkUserName = findView(R.id.base_course_file_item_homework_upload_user_name);
        tvHomeworkSize = findView(R.id.base_course_file_item_size_homework);
        ivHomeworkPlay.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onPlay();
            }
        });
        ivHomeworkDelete.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onDelete(mHomeworkModel.getHomeworkId());
            }
        });
        ivHomeworkOpenFile.setOnClickListener(v -> {
            // 打开文件前先检查文件状态
            File file = checkHomeworkFile(mHomeworkModel);
            if (file == null || homeworkDownloadState != HomeworkDownloadState.HasDownload) {
                // 重置下载进度
                updateDownloadProgress(0);
            } else {
                // 跳转打开此文件
                BaseUIUtils.openFileInSystem(mContext, file);
            }
        });
        ivHomeworkDownloadProgress.setOnClickListener(v -> {
            if (homeworkDownloadState == HomeworkDownloadState.DownloadFailed) {
                resetDownLoadProgress();
            }
            // 每次点击下载时需要先检查一次
            File file = checkHomeworkFile(mHomeworkModel);
            if (file == null || homeworkDownloadState == HomeworkDownloadState.HasDownload) {
                // 如果点击时检查文件已存在
                return;
            }
            if (homeworkDownloadState != HomeworkDownloadState.Downloading) {
                // 如果不在下载状态，开始下载
                try {
                    boolean createRst = file.createNewFile();
                    if (createRst && onItemClickListener instanceof IOnHomeworkItemClickListener) {
                        updateDownloadProgress(0.01f);
                        ((IOnHomeworkItemClickListener) onItemClickListener).onDownload(file);
                    } else {
                        LPLogger.d(tag, "文件创建失败");
                    }
                } catch (IOException e) {
                    LPLogger.d(tag, "文件创建失败 : " + e.getMessage());
                    e.printStackTrace();
                }
            } else {
                // 点击时，存在中下载文件，正在下载中，删除下载文件，取消下载
                ((IOnHomeworkItemClickListener) onItemClickListener).onCancelDownload(file);
            }
        });
    }

    private HomeworkDownloadState homeworkDownloadState = HomeworkDownloadState.NotExit;

    /**
     * 检查当前作业文档状态，更新数据及视图状态
     */
    public File checkHomeworkFile(LPHomeworkModel homeworkModel) {
        if (homeworkModel == null) {
            return null;
        }
        homeworkDownloadState = HomeworkDownloadState.NotExit;
        String fileName = BaseUIUtils.getHomeworkFileName(homeworkModel);
        File dir = new File(homeworkDirPath);
        boolean createRst = false;
        if (!dir.exists()) {
            createRst = dir.mkdir();
        }
        if (!dir.exists() && !createRst) {
            return null;
        }
        File homeworkFile = new File(homeworkDirPath + fileName + homeworkModel.getFext());
        if (homeworkFile.exists()) {
            // 如果存在已经下载好的
            ivHomeworkDownloadProgress.setVisibility(GONE);
            ivHomeworkDownload.setVisibility(INVISIBLE);
            ivHomeworkOpenFile.setVisibility(VISIBLE);
            homeworkDownloadState = HomeworkDownloadState.HasDownload;
            return homeworkFile;
        }
        if (TextUtils.isEmpty(homeworkModel.getFext())) {
            return null;
        }
        File homeworkFileDownloading = new File(homeworkDirPath + fileName);
        if (homeworkFileDownloading.exists()) {
            // 如果之前有下载中的文件
            ivHomeworkDownloadProgress.setVisibility(VISIBLE);
            ivHomeworkDownload.setVisibility(VISIBLE);
            ivHomeworkOpenFile.setVisibility(GONE);
            homeworkDownloadState = HomeworkDownloadState.Downloading;
            return homeworkFileDownloading;
        } else {
            ivHomeworkDownloadProgress.setVisibility(VISIBLE);
            ivHomeworkDownload.setVisibility(VISIBLE);
            ivHomeworkOpenFile.setVisibility(GONE);
            homeworkDownloadState = HomeworkDownloadState.NotExit;
            return homeworkFileDownloading;
        }
    }

    public HomeworkDownloadState getHomeworkDownloadState() {
        return homeworkDownloadState;
    }
    // endregion

    private <T extends View> T findView(int id) {
        return mView.findViewById(id);
    }
}
